﻿using System.Collections.Generic;
using UnityEngine.Events;

public class MessageManager : ModuleBase<MessageManager>
{
    public Dictionary<MessageDefine, List<MessageListen>> MessageListeners;

    public override void Init()
    {
        MessageListeners = new Dictionary<MessageDefine, List<MessageListen>>();
    }

    /// <summary>
    /// 添加消息监听
    /// </summary>
    /// <param name="view"></param>
    /// <param name="msg"></param>
    /// <param name="func"></param>
    public void AddListener(object listener, MessageDefine msg, UnityAction<object> func)
    {
        if (listener == null || func == null)
            throw new System.Exception("listener or func is null");

        List<MessageListen> listeners;
        if (MessageListeners.ContainsKey(msg))
        {
            listeners = MessageListeners[msg];
        }
        else
        {
            listeners = new List<MessageListen>();
            MessageListeners[msg] = listeners;
        }

        MessageListen mListen = null;
        foreach (var lis in listeners)
        {
            if (lis.Listener == listener)
            {
                mListen = lis;
                mListen.Func = func;
                break;
            }
        }
        if (mListen == null)
        {
            mListen = new MessageListen(listener, func);
            listeners.Add(mListen);
        }
    }

    public void SendMessage(MessageDefine msg, object data = null)
    {
        if (MessageListeners.ContainsKey(msg))
        {
            List<MessageListen> listeners = MessageListeners[msg];
            foreach (var listener in listeners)
            {
                if (listener.Listener != null)
                    listener.Func(data);
            }
        }
    }

    public void RemoveListener(object listener)
    {
        foreach (var listeners in MessageListeners.Values)
        {
            for (int i = listeners.Count - 1; i >= 0; i--)
            {
                var lis = listeners[i];
                if (lis.Listener == listener)
                {
                    listeners.RemoveAt(i);
                    break;
                }
            }
        }
    }

    public void RemoveMessage(MessageDefine msg)
    {
        if (MessageListeners.ContainsKey(msg))
            MessageListeners.Remove(msg);
    }

    public void ClearListeners()
    {
        MessageListeners.Clear();
    }

    public override void Dispose()
    {
        ClearListeners();
    }
}

public class MessageListen
{
    public object Listener;
    public UnityAction<object> Func;

    public MessageListen(object lis, UnityAction<object> func)
    {
        Listener = lis;
        Func = func;
    }
}